← Back

WEB STORAGE IN JAVASCRIPT

Web Storage lets web applications store and retrieve data on the client side, meaning in the user's browser.

This note explains browser storage in simple language.

You will learn:

  1. what cookies are
  2. what Web Storage is
  3. the difference between localStorage and sessionStorage
  4. how to save, read, and remove data
  5. why JSON is needed
  6. how to save form data while the user is typing

1. Why browser storage exists

A website often needs to remember something about the user, for example:

In the past, websites mainly used the HTTP protocol, which is stateless. That means a website could not naturally remember user-related information between requests unless extra mechanisms were used.

Diagram 1. Why storage is needed

User visits website
↓
does something
↓
website wants to remember it
↓
browser storage is used

Without storage, many websites would forget user choices every time the page reloads.

2. Cookies

Cookies were one of the first ways to store small pieces of data in the browser.

A cookie stores data as a key-value pair and also has an expiration time. After that time, the browser deletes it automatically.

Both the browser and the server can set and read cookies, and cookies can be sent automatically with HTTP requests. This makes them useful for recognizing user-related information on the server side.

Diagram 2. Cookie idea

Website / server
↓
stores small text data in browser
↓
cookie = key + value + expiration time

Cookies are still used today, but they have limitations, especially for frontend work.

3. Why cookies are not always enough

Cookies are limited because:

That is why browsers now provide Web Storage.

4. What is Web Storage?

Web Storage is a browser mechanism that lets web applications store and retrieve data on the client side, meaning on the user's computer.

It is useful for remembering interface state and user preferences between actions or visits.

Examples:

Important warning: Web Storage should not store sensitive data such as passwords or bank card numbers, because if a malicious script gets access to the page, it can read this data.

Diagram 3. Web Storage meaning

Web app
↓
stores data in browser
↓
can restore state later

Web Storage is mainly for practical client-side state, not for secret information.

5. Two types of Web Storage

Web Storage has two main parts:

Diagram 4. Two storage types

Web Storage
│
├─ localStorage
└─ sessionStorage

6. localStorage

localStorage stores data for a website and keeps it even after:

The data stays there until it is removed manually, cleared in browser settings, or deleted with JavaScript.

Data is shared across tabs and windows of the same domain.

It usually stores about 5 MB to 10 MB depending on the browser, which is much more than cookies.

Diagram 5. localStorage

Save data
↓
close tab
↓
open browser later
↓
data is still there

Use localStorage when you want the data to stay for a long time.

7. sessionStorage

sessionStorage stores data only while the current browser tab or window is open.

If the user closes that tab or window, the stored data is deleted automatically. Every tab gets its own session storage.

Diagram 6. sessionStorage

Save data in tab
↓
tab stays open
↓
data exists

Close tab
↓
data is deleted

Use sessionStorage for temporary data that should disappear after the tab is closed.

8. localStorage vs sessionStorage

localStorage

sessionStorage

Diagram 7. Main difference

localStorage
↓
persistent

sessionStorage
↓
only for current tab session

9. Accessing localStorage

You can access it through the window object:

console.log(window.localStorage);

You can also use it directly:

console.log(localStorage);

At first it may look like this:

Storage {length: 0}

That means it is currently empty.

Diagram 8. Accessing storage

window.localStorage
or
localStorage
↓
Storage object

10. Saving data with setItem()

To save data in localStorage, use:

localStorage.setItem(key, value);

Example

localStorage.setItem("ui-theme", "light");

This creates a storage entry with:

If the key already exists, its value is overwritten.

Diagram 9. setItem()

setItem("ui-theme", "light")
↓
key = "ui-theme"
value = "light"
↓
stored in browser

11. Reading data with getItem()

To read data, use:

localStorage.getItem(key);

Example

const savedTheme = localStorage.getItem("ui-theme");

console.log(savedTheme); // "light"

If the key does not exist, the result is null.

Diagram 10. getItem()

getItem("ui-theme")
↓
if key exists → value
if key does not exist → null

12. Removing data

To remove one entry, use:

localStorage.removeItem(key);

Example

localStorage.setItem("ui-theme", "dark");
localStorage.removeItem("ui-theme");

After removal, trying to read that key returns null.

To clear everything, use:

localStorage.clear();

Clearing all storage is risky because it may delete data created by other parts of the project. It is usually better to remove only the specific keys you do not need.

Diagram 11. Removing vs clearing

removeItem("key")
↓
remove one entry

clear()
↓
remove all entries

clear() is powerful, but often too aggressive.

13. Only strings are stored directly

Web Storage stores values as strings.

That means if you save numbers, arrays, or objects, you must convert them into strings first.

For complex data, use:

JSON.stringify(...)

Diagram 12. Complex data storage

Object or array
↓
JSON.stringify(...)
↓
string
↓
save to storage

14. Saving complex data

Example

const settings = {
  theme: "dark",
  isAuthenticated: true,
  options: [1, 2, 3],
};

localStorage.setItem("settings", JSON.stringify(settings));

This works because the object is converted into a string before saving.

15. Reading complex data back

When you read complex data from storage, you get a string first.

Then you need JSON.parse() to turn that string back into a real object or array.

Example

const savedSettings = localStorage.getItem("settings");
console.log(savedSettings); // string

const parsedSettings = JSON.parse(savedSettings);
console.log(parsedSettings); // object

Diagram 13. Read complex data

getItem("settings")
↓
JSON string
↓
JSON.parse(...)
↓
real object

Easy rule:

Save complex data → stringify
Read complex data → parse

16. sessionStorage methods

sessionStorage uses the same methods as localStorage:

The only difference is the lifetime of the data.

Example

sessionStorage.setItem("user-id", "123");
sessionStorage.setItem(
  "tickets",
  JSON.stringify({ from: "Lviv", to: "Kyiv", quantity: 2 })
);

const userId = sessionStorage.getItem("user-id");
const tickets = JSON.parse(sessionStorage.getItem("tickets"));

Diagram 14. sessionStorage flow

sessionStorage.setItem(...)
↓
data exists in current tab
↓
close tab
↓
data disappears

17. Good use cases for localStorage

localStorage is good for longer-term app state, for example:

Diagram 15. Good use cases for localStorage

Need data later?
Need it after browser close?
↓
use localStorage

18. Good use cases for sessionStorage

sessionStorage is good for temporary session state, for example:

For example, separate article or blog tabs can keep their own temporary state without affecting each other.

Diagram 16. Good use cases for sessionStorage

Need data only in this tab?
Need it only for this session?
↓
use sessionStorage

19. Case study: feedback form

The lesson gives a practical example with this HTML:

<form class="feedback-form">
  <textarea name="message"></textarea>
  <button type="submit">Send feedback</button>
</form>

At first, if the user types text and reloads the page before submitting, the message is lost.

So the solution is:

  1. save the current text while the user types
  2. restore it when the page reloads
  3. remove it after successful submit

Diagram 17. Feedback form problem

User types message
↓
reloads page
↓
message disappears

20. Saving the text while typing

The lesson uses input on the form and stores the current textarea value in localStorage.

Example

const form = document.querySelector(".feedback-form");
const localStorageKey = "nikitagoluban-feedback-message";

form.addEventListener("input", evt => {
  localStorage.setItem(localStorageKey, evt.target.value);
});

This uses event delegation: the form catches the input event, and evt.target.value gives the current value of the field being edited.

Diagram 18. Save while typing

User types
↓
input event
↓
current value saved to localStorage

21. Removing the saved value after submit

When the form is submitted:

Example

const form = document.querySelector(".feedback-form");
const localStorageKey = "nikitagoluban-feedback-message";

form.addEventListener("input", evt => {
  localStorage.setItem(localStorageKey, evt.target.value);
});

form.addEventListener("submit", evt => {
  evt.preventDefault();
  console.log(evt.target.elements.message.value);
  localStorage.removeItem(localStorageKey);
  form.reset();
});

Diagram 19. Submit flow

User submits form
↓
preventDefault()
↓
read message
↓
remove saved data from localStorage
↓
reset form

22. Restoring the saved value on page load

To restore the text after reload, read it from storage when the page loads and set it as the initial value of the textarea.

Example

const form = document.querySelector(".feedback-form");
const textarea = form.elements.message;
const localStorageKey = "nikitagoluban-feedback-message";

textarea.value = localStorage.getItem(localStorageKey) ?? "";

form.addEventListener("input", evt => {
  localStorage.setItem(localStorageKey, evt.target.value);
});

form.addEventListener("submit", evt => {
  evt.preventDefault();
  console.log(evt.target.elements.message.value);
  localStorage.removeItem(localStorageKey);
  form.reset();
});

The ?? "" part means:

Diagram 20. Full feedback form logic

Page loads
↓
read saved value from localStorage
↓
put value into textarea

User types
↓
save new value

User submits
↓
remove saved value
↓
reset form

This creates a much better user experience because the typed text is not lost after reload.

23. Easy memory rules

Cookies = small browser storage with expiration
Web Storage = browser storage for client-side data

localStorage = long-term
sessionStorage = current tab only

setItem() = save
getItem() = read
removeItem() = remove one
clear() = remove all

Complex data:
save → JSON.stringify()
read → JSON.parse()

24. Quick summary

25. Final conclusion

If you understand these ideas:

cookies
Web Storage
localStorage
sessionStorage
setItem()
getItem()
removeItem()
clear()
JSON.stringify()
JSON.parse()

then you already have a strong foundation for browser storage in JavaScript.

This topic is very important because real web applications constantly need to remember user state on the client side.

← Back